<template>
  <div class="user-management-container">
    <!-- 搜索栏 -->
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
<!--        <el-form-item label="状态">-->
<!--          <el-select v-model="searchForm.isActive" clearable>-->
<!--            <el-option label="启用" :value="0" />-->
<!--            <el-option label="禁用" :value="1" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" @click="loadUsers">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 用户表格 -->
    <el-card shadow="never" class="mt-4">
      <el-table :data="userList" border stripe>
        <el-table-column prop="userId" label="用户ID" width="120" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="phone" label="手机号" width="150" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="{row}">
            {{ row.gender === "1" ? '男' : row.gender === "0" ? '女' : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="isActive" label="状态" width="100">
          <template #default="{row}">
            <el-tag :type="row.isActive ? 'danger' : 'success'">
              {{ row.isActive ? '已禁用' : '已启用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{row}">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button
              size="small"
              :type="row.isActive ? 'success' : 'danger'"
              @click="toggleStatus(row)">
              {{ row.isActive ? '启用' : '禁用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        class="mt-4"
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        @current-change="loadUsers"
        layout="total, prev, pager, next" />
    </el-card>

    <!-- 编辑抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      title="编辑用户信息"
      size="40%"
      destroy-on-close>
      <el-form
        :model="currentUser"
        label-width="100px"
        :rules="formRules"
        ref="formRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="currentUser.username" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="currentUser.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="currentUser.email" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="currentUser.gender">
            <el-radio :label="0">女</el-radio>
            <el-radio :label="1">男</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="头像" prop="avatarUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess">
            <img v-if="currentUser.avatarUrl" :src="currentUser.avatarUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存修改</el-button>
          <el-button @click="drawerVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { UserAPI } from '@/common/net/api'

interface User {
  userId: number
  username: string
  phone: string
  email?: string
  gender?: number
  avatarUrl?: string
  isActive?: number
}

interface UserQueryParams {
  username?: string
  phone?: string
  isActive?: number
  current: number
  size: number
}

// 搜索表单
const searchForm = reactive({
  username: '',
  phone: '',
  isActive: undefined as number | undefined
})

// 分页参数
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 用户数据和UI状态
const userList = ref<User[]>([])
const currentUser = ref<Partial<User>>({})
const drawerVisible = ref(false)
const formRef = ref<FormInstance>()

// 表单验证规则
const formRules = reactive<FormRules>({
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效手机号', trigger: 'blur' }
  ]
})

// 加载用户数据
const loadUsers = async () => {
  try {
    const params: UserQueryParams = {
      ...searchForm,
      current: pagination.current,
      size: pagination.size
    }

    const { data } = await UserAPI.getList(params)
    userList.value = data.data.records
    pagination.total = data.data.total
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  }
}

// 编辑用户
const handleEdit = (user: User) => {
  currentUser.value = { ...user }
  drawerVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value?.validate()
    await UserAPI.update(currentUser.value)
    ElMessage.success('更新成功')
    drawerVisible.value = false
    loadUsers()
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

// 切换用户状态
const toggleStatus = async (user: User) => {
  try {
    const apiMethod = user.isActive ? UserAPI.enable : UserAPI.disable
    await apiMethod(user.userId)
    ElMessage.success(`用户已${user.isActive ? '启用' : '禁用'}`)
    loadUsers()
  } catch (error) {
    ElMessage.error('状态修改失败')
  }
}

// 初始化加载
onMounted(() => {
  loadUsers()
})
</script>
<style scoped>
.avatar-uploader :deep(.avatar) {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
